// 发布订阅
export class EventEmitter {
    constructor() {
      this.event = {};
    }
  
    on(type, cbRes, cbRej) {
      if (!this.event[type]) {
        this.event[type] = [[cbRes, cbRej]];
      } else {
        this.event[type].push([cbRes, cbRej]);
      }
    }
  
    emit(type, res, ansType) {
      if (!this.event[type]) return;
      this.event[type].forEach((cbArr) => {
        if (ansType === "resolve") {
          cbArr[0](res);
        } else {
          cbArr[1](res);
        }
      });
    }
  }
  
  // 根据请求生成对应的key
  export function generateReqKey(config, hash) {
    const { method, url, params, data } = config;
    return [method, url, JSON.stringify(params), JSON.stringify(data), hash].join(
      "&"
    );
  }
  
  // 存储已发送但未响应的请求
  export const pendingRequest = new Set();
  // 发布订阅容器
  export const ev = new EventEmitter();
  
  // 接口响应成功
  export function handleSuccessResponse_limit(response) {
    const reqKey = response.config.pendKey;
    if (pendingRequest.has(reqKey)) {
      let x = null;
      try {
        x = JSON.parse(JSON.stringify(response));
      } catch (e) {
        x = response;
      }
      pendingRequest.delete(reqKey);
      ev.emit(reqKey, x, "resolve");
      delete ev.event[reqKey];
    }
  }
  
  // 接口走失败响应
  export function handleErrorResponse_limit(error) {
    if (error.type && error.type === "limitResSuccess") {
      return Promise.resolve(error.val);
    } else if (error.type && error.type === "limitResError") {
      return Promise.reject(error.val);
    } else {
      const reqKey = error.config.pendKey;
      if (pendingRequest.has(reqKey)) {
        let x = null;
        try {
          x = JSON.parse(JSON.stringify(error));
        } catch (e) {
          x = error;
        }
        pendingRequest.delete(reqKey);
        ev.emit(reqKey, x, "reject");
        delete ev.event[reqKey];
      }
    }
    // return Promise.reject(error);
    return Promise.resolve(error);
  }
  
 

  